/**
 * components util
 */
import i18n from '@/lang'
import {
  ACCESS_TOKEN
} from '@/store/mutationTypes'
import notification from 'ant-design-vue/es/notification'
import { saveAs } from 'file-saver'
import streamSaver from 'streamsaver'
/**
 * 清理空值，对象
 * @param children
 * @returns {*[]}
 */
export function filterEmpty(children = []) {
  return children.filter(c => c.tag || (c.text && c.text.trim() !== ''))
}

/**
 * 获取字符串长度，英文字符 长度1，中文字符长度2
 * @param {*} str
 */
export const getStrFullLength = (str = '') =>
  str.split('').reduce((pre, cur) => {
    const charCode = cur.charCodeAt(0)
    if (charCode >= 0 && charCode <= 128) {
      return pre + 1
    }
    return pre + 2
  }, 0)

/**
 * 截取字符串，根据 maxLength 截取后返回
 * @param {*} str
 * @param {*} maxLength
 */
export const cutStrByFullLength = (str = '', maxLength) => {
  let showLength = 0
  return str.split('').reduce((pre, cur) => {
    const charCode = cur.charCodeAt(0)
    if (charCode >= 0 && charCode <= 128) {
      showLength += 1
    } else {
      showLength += 2
    }
    if (showLength <= maxLength) {
      return pre + cur
    }
    return pre
  }, '')
}
/**
 * 下载文件流
 * @param {文件流} data
 */
export const downloadBlobFile = (data, fileName = '') => {
  const blob = data;
  console.log(data, 'data');
  if (blob.type === 'application/json') {
    blob.text().then(text => {
      const obj = JSON.parse(text)
      notification.info({
        message: i18n.t('downFileTip'),
        description: obj.message
      })
    })
    return
  }
  saveAs(blob, fileName)
}

/**
 * 下载文件流(fetch+streamSaver文件读取)
 */
export const writeFileStream = (url, fileName = 'noName.txt') => {
  const token = sessionStorage.getItem(ACCESS_TOKEN)
  fetch(url, {
    method: 'POST',
    cache: 'no-cache',
    headers: {
      'Access-Token': token
    },
    mode: 'cors'
    // eslint-disable-next-line consistent-return
  }).then(res => {
    const fileStream = streamSaver.createWriteStream(fileName, {
      size: res.headers.get('content-length')
    })
    const readableStream = res.body
    if (window.WritableStream && readableStream.pipeTo) {
      return readableStream.pipeTo(fileStream)
        .then(() => console.log('done writing'))
    }
    window.writer = fileStream.getWriter()
    const reader = res.body.getReader()
    const pump = () => reader.read()
      .then(res => res.done
        ? window.writer.close()
        : window.writer.write(res.value).then(pump))
    return pump()
  })
}
/**
 * 根据当前语言包设置echarts对应的语言
 * @lang 是本应用中设置的语言包,有一个问题echarts没有繁体语言
*/
export const getEchartNameMap = (lang) => {
  if (lang === 'en') {
    return 'en'
  }
  return 'cn'
}
